//
//  TwERPGongdan.m
//  TwERP
//
//  Created by Xiangyang Li on 12-7-2.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "TwERPGongdan.h"

#import "TwERPJsonAgent.h"
#import "TwERPAttachedFile.h"

@interface TwERPGongdan ()
@property (nonatomic,strong) TwERPGongdan * oldCopy;

@end

@implementation TwERPGongdan

@synthesize oldCopy =_oldCopy;

@synthesize gdNo=_gdNo;

@synthesize category=_category;
@synthesize receptionTime=_receptionTime;
@synthesize wishFixedTime =_wishFixedTime;
@synthesize fixedTime = _fixedTime;
@synthesize problemDescription = _problemDescription;
@synthesize serviceAssistant = _serviceAssistant;
@synthesize gls = _gls;
@synthesize nextTime = _nextTime;
@synthesize jywxxm = _jywxxm;

@synthesize memo = _memo;
@synthesize isJiesuan =_isJiesuan;

@synthesize vehicle =_vehicle;
@synthesize labourItems = _labourItems;
@synthesize partItems = _partItems;
@synthesize attachedFiles = _attachedFiles;

@synthesize vehSurface = _vehSurface;


- (NSMutableString *)vehSurface
{
    if (_vehSurface == nil || [_vehSurface length]<10) 
    {
        unichar uch[520];
        for (int i=0; i<520; i++) uch[i]='0';
        _vehSurface = [[NSMutableString alloc] initWithCharacters:uch length:520];
    }
    return _vehSurface;

}
- (void) setVehSurface:(NSString *)vehSurface
{
    if ( [vehSurface length]<10) 
    {
        unichar uch[520];
        for (int i=0; i<520; i++) uch[i]='0';
        _vehSurface = [[NSMutableString alloc] initWithCharacters:uch length:520];
    }else {
        _vehSurface = [vehSurface mutableCopy];
    }
    
}
- (TwERPVehicle *)vehicle
{
    if (_vehicle == nil) _vehicle = [[TwERPVehicle alloc] init];
    return _vehicle;
}
- (NSArray *)attachedFiles
{
    if (_attachedFiles == nil) _attachedFiles = [[NSArray alloc] init];
    return _attachedFiles;
    
}
- (NSArray *)labourItems
{
    if (_labourItems == nil) _labourItems = [[NSArray alloc] init];
    return _labourItems;
    
}

- (NSArray *)partItems
{
    if (_partItems == nil) _partItems = [[NSArray alloc] init];
    return _partItems;
    
}

- (float)sumOfLabourItems
{
    float sum=0;
    
    for (TwERPLabourItem * lItem in self.labourItems) {
        sum+=lItem.price*lItem.quantity;
    }
    return sum;
}
- (float)sumOfPartItems
{
    float sum=0;
    
    for (TwERPPartItem * pItem in self.partItems) {
        sum+=pItem.price*pItem.quantity;
    }
    return sum;
}

-(float)sumOfItems
{
    return [self sumOfLabourItems]+[self sumOfPartItems];
}

-(void) setReceptionTime:(id)receptionTime
{

     if ([receptionTime isKindOfClass:[NSDate class]])
         _receptionTime = receptionTime;
    else if  ([receptionTime isKindOfClass:[NSString class]])
    {
        _receptionTime =[self stringToDate:receptionTime];
    }
         
}

-(void) setWishFixedTime:(id)wishFixedTime
{
    
    if ([wishFixedTime isKindOfClass:[NSDate class]])
        _wishFixedTime = wishFixedTime;
    else if  ([wishFixedTime isKindOfClass:[NSString class]])
    {
        _wishFixedTime = [self stringToDate:wishFixedTime];
    }
    
}

-(void) setFixedTime:(id)fixedTime
{
    
    if ([fixedTime isKindOfClass:[NSDate class]])
        _fixedTime = fixedTime;
    else if  ([fixedTime isKindOfClass:[NSString class]])
    {
        _fixedTime = [self stringToDate:fixedTime];
    }
    
}

-(void) setNextTime:(id)nextTime
{
    
    if ([nextTime isKindOfClass:[NSDate class]])
        _nextTime = nextTime;
    else if  ([nextTime isKindOfClass:[NSString class]])
    {
        _nextTime = [self stringToDate:nextTime];
    }
    
}

-(void) setVehicle:(id)vehicle
{
    
    if ([vehicle isKindOfClass:[TwERPVehicle class]])
        _vehicle = vehicle;
    else if  ([vehicle isKindOfClass:[NSDictionary class]])
    {
        _vehicle = [[TwERPVehicle alloc] init];
        [_vehicle setValuesForKeysWithDictionary:vehicle];
    }
    
}

-(void) setLabourItems:(NSArray *)labourItems
{
    NSMutableArray * lItems = [[NSMutableArray alloc ] init];
    for (id lItem in labourItems)
    {
        if ([lItem isKindOfClass:[TwERPLabourItem class]])
            [lItems addObject:lItem];
        else if  ([lItem isKindOfClass:[NSDictionary class]])
        {
            TwERPLabourItem *lbItem =[[TwERPLabourItem alloc] init];
            [lbItem setValuesForKeysWithDictionary:lItem];
            [lItems addObject:lbItem];
        }

    }
    
    _labourItems = [lItems mutableCopy];
}

-(void) setPartItems:(NSArray *)partItems
{
    NSMutableArray * pItems = [[NSMutableArray alloc ] init];
    for (id pItem in partItems)
    {
        if ([pItem isKindOfClass:[TwERPPartItem class]])
            [pItems addObject:pItem];
        else if  ([pItem isKindOfClass:[NSDictionary class]])
        {
            TwERPPartItem *parItem =[[TwERPPartItem alloc] init];
            [parItem setValuesForKeysWithDictionary:pItem];
            [pItems addObject:parItem];
        }
        
    }
    
    _partItems = [pItems mutableCopy];
}
-(void) setAttachedFiles:(NSArray *)attachedFiles
{
    NSMutableArray * pItems = [[NSMutableArray alloc ] init];
    for (id pItem in attachedFiles)
    {
        if ([pItem isKindOfClass:[TwERPAttachedFile class]])
            [pItems addObject:pItem];
        else if  ([pItem isKindOfClass:[NSDictionary class]])
        {
            TwERPAttachedFile *parItem =[[TwERPAttachedFile alloc] init];
            [parItem setValuesForKeysWithDictionary:pItem];
                parItem.downloading = YES;
            [pItems addObject:parItem];
        }
        
    }
    
    _attachedFiles = [pItems mutableCopy];
}

+ (TwERPGongdan *) createGongdanWithCphm:(NSString *)cphm
{
    TwERPGongdan * gd =[[TwERPGongdan alloc] initWithNewId];
    //gd.gdId = [TwERPJsonAgent newGdId];
    gd.gdNo = @"新增工单";
    gd.receptionTime = [NSDate date];
    gd.category =@"未定义";
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    gd.wishFixedTime = [[NSDate alloc]
                        initWithTimeIntervalSinceNow:secondsPerDay*3];
   // gd.nextTime = [[NSDate alloc] init];
   // gd.fixedTime = [[NSDate alloc] init];
    
    TwERPVehicle * toGet = [TwERPVehicle getVehicleByCphm:cphm];

    if(toGet == nil) {
        gd.vehicle = [[TwERPVehicle alloc] initWithNewId];
        gd.vehicle.licenseNo =[[TwERPJsonAgent getCpHeader] stringByAppendingString:cphm];
        gd.vehicle.customer = [[TwERPCustomer alloc] initWithNewId];
    }else
        gd.vehicle = toGet;
    gd.isJiesuan =NO;
    gd.operationState = GdInsert;
    return gd;
    
}
-(NSString *) commit
{
   /* TwERPVehicle * toGet = [TwERPVehicle getVehicleByCphm: self.vehicle.licenseNo];
    
    if(toGet != nil) 
        self.vehicle = toGet;
    这段导致电话号码未保存，其实是所有新编辑的车辆客户信息都不能保存
    */
    return [super commit];
}
- (void) refresh
{
    NSDictionary *newGdDict= [TwERPJsonAgent getGongdanById:self.entityId];
    [self setValuesForKeysWithDictionary:newGdDict];
}
- (BOOL) prepairForEdit
{
    if(self.operationState == GdInsert || self.operationState == GdEdit) return YES;
    if (self.isJiesuan) return NO;
    if (self.operationState == GdBrowse || self.operationState == GdUploading) {
        self.oldCopy = [[TwERPGongdan alloc] init];
        [self.oldCopy setValuesForKeysWithDictionary:[self transFormToDictionary]];
    }
    self.operationState = GdEdit;
    return YES;
}
- (void) cancelEdit
{
    if(self.operationState == GdInsert) return;
    [self setValuesForKeysWithDictionary:[self.oldCopy transFormToDictionary]];
    self.oldCopy = nil;
    self.operationState = GdBrowse;
}

- (TwERPLabourItem *)appendLabourItem
{
    NSMutableArray * tempItems = [[NSMutableArray alloc] initWithArray:self.labourItems];
    TwERPLabourItem * lItem =[[TwERPLabourItem alloc] initWithNewId];
    [tempItems addObject:lItem];
    self.labourItems = tempItems;
    return lItem;
}
- (TwERPPartItem *)appendPartItem
{
    NSMutableArray * tempItems = [[NSMutableArray alloc] initWithArray:self.partItems];
    TwERPPartItem * lItem =[[TwERPPartItem alloc] initWithNewId];
    [tempItems addObject:lItem];
    self.partItems = tempItems;
    return lItem;
}

- (void) addLabourItem:(id)lItem
{
    NSMutableArray * tempItems = [[NSMutableArray alloc] initWithArray:self.labourItems];
    TwERPLabourItem *lItem1 = (TwERPLabourItem *)lItem;
    lItem1.entityId = 0;
    
    [tempItems addObject:lItem];
    self.labourItems = tempItems;
}
- (void) addPartItem:(id)pItem;
{
    TwERPPartItem *partItem = (TwERPPartItem *)pItem;
    partItem.quantity=1;
    partItem.entityId = 0; //[TwERPJsonAgent idOfEntityType:[partItem class].description];
    NSMutableArray * tempItems = [[NSMutableArray alloc] initWithArray:self.partItems];
    [tempItems addObject:partItem];
    self.partItems = tempItems; 
}

- (void) addAttachedFile:(id)aItem;
{
    TwERPAttachedFile *partItem = (TwERPAttachedFile *)aItem;
    
    NSMutableArray * tempItems = [[NSMutableArray alloc] initWithArray:self.attachedFiles];
    [tempItems addObject:partItem];
    self.attachedFiles = tempItems;
}



-(NSDictionary *)transFormToDictionary
{
    [self validateEntityId];
    NSMutableDictionary * gdic=[[NSMutableDictionary alloc] initWithDictionary:[self dictionaryWithValuesForKeys:[self allKeys]]];
    

    [gdic setValue:[self dateToString:self.receptionTime] forKey:@"receptionTime"];
     [gdic setValue:[self dateToString:self.wishFixedTime] forKey:@"wishFixedTime"];
        [gdic setValue:[self dateToString:self.fixedTime] forKey:@"fixedTime"];
      [gdic setValue:[self dateToString:self.nextTime] forKey:@"nextTime"];
    
    [gdic setValue:[self.vehicle transFormToDictionary] forKey:@"vehicle"];
 
    NSMutableArray * lDicItems = [[NSMutableArray alloc] initWithCapacity:self.labourItems.count];
    for (int i=0; i<self.labourItems.count; i++) {
        TwERPLabourItem * lItem=[self.labourItems objectAtIndex:i];
        [lDicItems addObject:[lItem transFormToDictionary]]; 
    }
    [gdic setValue:lDicItems forKey:@"labourItems"];
    
    NSMutableArray * pDicItems = [[NSMutableArray alloc] initWithCapacity:self.partItems.count];
    for (int i=0; i<self.partItems.count; i++) {
        TwERPPartItem * lItem=[self.partItems objectAtIndex:i];
        [pDicItems addObject:[lItem transFormToDictionary]]; 
    }
    [gdic setValue:pDicItems forKey:@"partItems"];  
    
    NSMutableArray * attachedItems = [[NSMutableArray alloc] initWithCapacity:self.attachedFiles.count];
    for (int i=0; i<self.attachedFiles.count; i++) {
        TwERPAttachedFile * lItem=[self.attachedFiles objectAtIndex:i];
        [attachedItems addObject:[lItem transFormToDictionary]]; 
    }
    
    [gdic setValue:attachedItems forKey:@"attachedFiles"];  
    
    [gdic removeObjectForKey:@"oldCopy"];
    

    return gdic;
}
-(void) downloadAttachedFiles
{
//    return;
    for (TwERPAttachedFile * af in self.attachedFiles) {
        [af downloadFromServer];
       
    }

}
-(BOOL) uploadAttachedFiles
{
  //upload and record exception to somewhere
    BOOL success=YES;
    for (TwERPAttachedFile * af in self.attachedFiles) {
        [af uploadToServer];
        success =success && ([af.uploadResult rangeOfString:@"success"].location != NSNotFound);
        
    }
    return success;
}

- (NSArray *) photoFiles
{
    NSMutableArray * af=[[NSMutableArray alloc] init];
    
    for (TwERPAttachedFile * aFile in self.attachedFiles) {
        if([aFile.type isEqualToString:@"image"])
            [af addObject:aFile];
            
    }
    return af;
}
- (NSArray *) audioFiles
{
    NSMutableArray * af=[[NSMutableArray alloc] init];
    for (TwERPAttachedFile * aFile in self.attachedFiles) {
        if([aFile.type isEqualToString:@"audio"])
            [af addObject:aFile];
    
    }
    return af;
}
@end
